<?php
/**
 * Static content controller.
 *
 * This file will render views from views/pages/
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('AppController', 'Controller');

/**
 * Static content controller
 *
 * Override this controller by placing a copy in controllers directory of an application
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers/pages-controller.html
 */
class PagesController extends AppController {

/**
 * Controller name
 *
 * @var string
 */
	public $name = 'Pages';

/**
 * This controller does not use a model
 *
 * @var array
 */
	public $helpers = array('Html', 'Form','Session');
    public $components = array('Session','Auth','Cookie');
    public $uses=array('User','Order','Ticket','Webhosting','Notification');

/**
 * Displays a view
 *
 * @param mixed What page to display
 * @return void
 */
	public function display($current_page=null,$skipsteps=null) {
		$path = func_get_args();

		$count = count($path);
		if (!$count) {
			$this->redirect('/');
		}
		$page = $subpage = $title_for_layout = null;

		if (!empty($path[0])) {
			$page = $path[0];
		}
		if (!empty($path[1])) {
			$subpage = $path[1];
		}
		if (!empty($path[$count - 1])) {
			//$title_for_layout = Inflector::humanize($path[$count - 1]);
            $title_for_layout='Главная страница';
		}
        //юзер решил пропустить шаги, чистим кук
        if($skipsteps=='skipsteps')
        {
          if(isset($_COOKIE['CakeCookie']['justregistered']))
          {
            $this->Cookie->destroy('justregistered');
            unset($_COOKIE['CakeCookie']['justregistered']);
          }
          if(isset($_COOKIE['CakeCookie']['Order']['steps']))
          {
            $this->Cookie->destroy('Order.steps');
            unset($_COOKIE['CakeCookie']['Order']['steps']);
          }
          //echo "123".$skipsteps;


        }
        /*echo "<pre>";
        print_r($_COOKIE);
        echo "</pre>"; */
        //юзер только что с реги, отправляем его на заказ
        //if(($this->Cookie->read('User.justregistered')=="true") || ($this->Cookie->read('Order.steps')=="true"))
        //if($this->Cookie->check('User.justregistered'))
        if(isset($_COOKIE['CakeCookie']['justregistered']) || isset($_COOKIE['CakeCookie']['Order']['steps']))
        //if(isset($_COOKIE['CakeCookie']['Order']['steps']))
        {
          $this->redirect(array('controller'=>'orders','action' => 'neworder'));
        }
        /*if(isset($_COOKIE['radiohost_order_id'])|| isset($_COOKIE['webhost_order_id']))
        {
          $this->redirect(array('controller'=>'orders','action' => 'setup'));
        } */
        $userid= $this->Auth->User('id');
        $this->set('user_name_sidebar', AppController::getUserName($userid));
        //notifications
        //$notifications=$this->Notification->findAllByUseridOrCircle($userid,'public',array(), array('Notification.id' => 'desc'),2);
        $notifications=$this->Notification->find('all',array(
                                    'conditions' => array('Notification.userid' => $userid,'Notification.onmain'=>'1'),
                                    'order' => array('Notification.id' => 'desc'),
                                    'limit'=>2));
        $notifications_public=$this->Notification->find('all',array(
                                    'conditions' => array('Notification.circle'=>'public','onmain'=>'1'),
                                    'order' => array('Notification.id' => 'desc'),
                                    'limit'=>1));
        $notifications=array_merge($notifications_public,$notifications);
        $this->set('notifications', $notifications);
        //$orders=$this->Order->findAllByUserid($userid);
        $orders=$this->Order->find('all',array(
                                    'conditions' => array('Order.userid' => $userid),
                                    'order' => array('Order.oplachenodo' => 'asc')));
        $this->set('orders', $orders);
        //$webhosting_orders=$this->Webhosting->findAllByUserid($userid);
        $webhosting_orders=$this->Webhosting->find('all',array(
                                    'conditions' => array('Webhosting.userid' => $userid),
                                    'order' => array('Webhosting.oplachenodo' => 'asc')));
        $this->set('webhosting_orders', $webhosting_orders);
        $active_orders=0;
        $not_active_orders=0;
        $need_pay_orders=0;
        $all_orders_cost=0;
        $autocontinue_one_of=0;
        //radiohost
        foreach($orders as $order)
        {
          $status=$order['Order']['status'];
          switch($status){
            case '0': $not_active_orders++; break;
            case '1': $need_pay_orders++; break;
            case '2': $active_orders++; break;
          }
          $all_orders_cost+=$order['Order']['cost'];
          if($order['Order']['autocontinue']==1)
            $autocontinue_one_of=1;
        }
        //webhost
        foreach($webhosting_orders as $order)
        {
          $status=$order['Webhosting']['status'];
          $all_orders_cost+=$order['Webhosting']['cost'];
          switch($status){
            case '0': $not_active_orders++; break;
            case '1': $need_pay_orders++; break;
            case '2': $active_orders++; break;
          }
        }
        $this->set('not_active_orders', $not_active_orders);
        $this->set('need_pay_orders', $need_pay_orders);
        $this->set('active_orders', $active_orders);
        $balancedata=AppController::getbalance($userid);
        $this->set('balance_value', $balancedata['balance']);
        $this->set('balance_time', $balancedata['time']);
        $this->set('all_orders_cost', $all_orders_cost);
        $need_money=$balancedata['balance']-$all_orders_cost;
        if($need_money<0)
            $this->set('need_money', -1*$need_money);
        else
            $this->set('need_money', $all_orders_cost);
        $this->set('autocontinue_one_of', $autocontinue_one_of);
        //news
        $this->Order->useDbConfig = 'wordpress_db';
        $news=$this->Order->query("SELECT * FROM  `wp_posts`,`wp_term_relationships` WHERE  `wp_posts`.`post_type` LIKE  'post' AND `wp_posts`.`post_status`='publish' AND `wp_term_relationships`.`object_id`=`wp_posts`.`id` AND `wp_term_relationships`.`term_taxonomy_id`='3'  ORDER BY `ID` DESC LIMIT 2");
        $this->set('news', $news);
        $this->Order->useDbConfig = 'default';
        //tickets
        $tickets=$this->Ticket->find('all',array(
                                    'limit'=>2,
                                    'conditions' => array('Ticket.userid =' =>$userid ),
                                    'order' => array('Ticket.id' => 'desc')));
        $this->set('tickets', $tickets);
        $ids=array('0'=>'Укажите ID заказа');
        foreach ($orders as $order)
        {
          $ids[$order['Order']['id']]= $order['Order']['id'];
          $ids[$order['Order']['id']]="Для заказа ID ".$ids[$order['Order']['id']];
        }
        $this->set('ids', $ids);
        $user_data=$this->User->findById($userid);
        $user_login=$user_data['User']['login'];
        $this->set('user_login', $user_login);

        $this->set(compact('page', 'subpage', 'title_for_layout'));
        //$path=str_replace("/skipsteps","",$path);
        //echo implode('/', $path);
		//$this->render(implode('/', $path));
        $this->render('home');
	}
    public function admindash()
    {
      $userid= $this->Auth->User('id');
      if(AppController::isAuthorized($userid))
      {
        $this->set('title_for_layout', 'Админцентр');
        $this->set('user_name_sidebar', AppController::getUserName($userid));
      }
      else
      {
        $this->Session->setFlash(__('У вас нет прав для просмотра этого раздела'));
        $this->redirect(array('controller'=>'pages','action' => 'index'));
      }
    }
}
